package com.zm.upload;

import com.zm.upload.bean.UploadPropertles;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
@ComponentScan("com.zm.upload")
@Slf4j
@ConditionalOnProperty(prefix = "upload",name = "enable",havingValue = "true")
public class UploadConfig implements WebMvcConfigurer {
    @Autowired
    UploadPropertles propertles;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        propertles.getMapper().forEach(mapper->{
            String webPath = mapper.getWebPath();
            String diskPath = mapper.getDiskPath();
            registry.addResourceHandler(webPath+"**")
                    .addResourceLocations("file:"+diskPath);
            File file = new File(diskPath);
            if (file.exists() == false){
                if (file.mkdirs() == false){
                    log.error("创建目录失败"+diskPath);
                }
            }
        });
    }

    //当前配置类对象的初始化方法
    //init-method   destory-method

    void init(){

    }
}
